var express = require("express");
var router = express.Router();
const jwt = require('jsonwebtoken');
let svgCaptcha = require("svg-captcha");
const { Aliba } = require('../AlibabaCloud/Alibaba.js');

const Dysmsapi20170525 = require('@alicloud/dysmsapi20170525');
var {
  FoodModel,
  FoodCateModel,
  registerModel,
  roomDingModel,
  HotelModel,
  roomModel,
  orderModel,
  vipPriceModel,
} = require("../model/db.js")
const axios = require("axios");
const app = express();
const port = 3001;
// 引入 cors 中间件
const cors = require("cors");
// 使用 cors 中间件
app.use(cors());

const TENCENTCLOUD_SECRET_ID = "AKIDCF5jFahdO0UlurcBZkjV3VnroX4NTM4Z";
const TENCENTCLOUD_SECRET_KEY = "KWUEl370gAQSGrGUWMzOaaNwKUVINHQO";
const COS = require("cos-nodejs-sdk-v5");

app.use(express.json());

// 初始化 COS 客户端
const cos = new COS({
  SecretId: TENCENTCLOUD_SECRET_ID,
  SecretKey: TENCENTCLOUD_SECRET_KEY,
});
// 添加请求体解析中间件
router.use(express.json()); // 解析 JSON 格式的请求体
router.use(express.urlencoded({ extended: true })); // 解析表单格式的请求体

var { FoodModel, FoodCateModel, registerModel } = require("../model/db.js");

// 注册
router.post("/register", async (req, res) => {
  const list = await registerModel.find({ username: req.body.username })
  if (list.length > 0) {
    res.send({
      code: 500,
      list
    })
  } else {
    await registerModel.create(req.body)
    res.send({
      code: 200,
      msg: "注册成功"
    })
  }


})




// 发送短信验证码
router.post('/sendSms', async (req, res) => {
  const { phone } = req.body;
  // await registerModel.create(req.body)
  const user = await registerModel.findOne({ phone });
  if (user) {
    // res.send({
    //   code:500
    // })
    res.status(400).json({ error: 'Invalid credentials' });
    return;
  }
  const code = Math.floor(Math.random() * 1000000)
  try {
    await Aliba(phone, code)
    console.log(1111);
    registerModel.create({ ...req.body, resetPasswordCode: code })
    // user.resetPasswordCode = code
    // user.save()
    res.send({ message: '验证码发送成功' })
  } catch (err) {
    res.status(500).send(err);
  }
});

// 验证短信验证码
router.post('/verify-code', async (req, res) => {
  const { phone, code } = req.body;
  console.log(phone, code);
  const user = await registerModel.findOne({ phone });
  console.log(user);
  if (!user) {
    res.status(400).json({ error: 'Invalid credentials' });
    return;
  }
  // 验证验证码
  if (user.resetPasswordCode == code) {
    res.send({ code: 200, msg: '验证码正确', data: user })
  } else {
    res.status(400).json({ error: '验证码错误' });
  }
});



//酒店查询
//获取数据
router.post('/hotel', async (req, res) => {
  let { currentPage, pageSize, sortField, sortOrder, addr, activePrice, activeType, title } = req.body
  //搜索
  console.log(activePrice);
  let arr = []
  if (addr != "" && addr != undefined) {
    arr.push({ city: addr })
  }
  if (activeType != "" && addr != undefined) {
    arr.push({ type: activeType })
  }


  if (activePrice != "" && activePrice != undefined) {
    const a = activePrice.split('-')
    console.log(a);

    const min = a[0]
    const max = a[1]
    arr.push({ newPirce: { $gte: min, $lte: max } })
  }
  if (title != "" && title != undefined) {
    arr.push({ title: { $regex: title } })
  }

  // if (carName != "") {
  //   arr.push({ title: { $regex: carName } })
  // }
  // if (carSort != "不限") {
  //   arr.push({ brand: { $regex: carSort } })
  // }
  // const a = price.split('-')
  // const min = a[0]
  // const max = a[1]
  // if (price != "不限") {
  //   arr.push({ price: { $gte: min, $lte: max } })
  // }

  //排序
  let sort = {};
  if (sortField && sortOrder) {
    sort[sortField] = sortOrder === 'asc' ? 1 : -1;
  }

  // 1 表示升序，-1 表示降序
  // let pubList = await pubModel.find({ $and: arr }).sort({ createdAt: 1 }).skip((currentPage - 1) * pageSize).limit(pageSize);

  let hotelList = await HotelModel.find({ $and: arr }).skip((currentPage - 1) * pageSize).limit(pageSize).sort(sort)

  let total = await HotelModel.countDocuments({ $and: arr })
  res.send({
    code: 200,
    hotelList,
    total
  })
})



router.get("/list", function (req, res) {
  console.log(req.query);
  res.send({
    code: 200,
    msg: "请求成功",
    data: [1, 2, 3, 4, 5],
  });
});

//获取酒店订单列表
router.post('/roomDingList', async function (req, res) {
  let list = await orderModel.find()
  res.send({
    list,
    code: 200
  })
});

//修改订单是否入住
router.post('/updateRoom', async (req, res) => {
  try {
    const { _id, status } = req.body;
    const result = await orderModel.updateOne(
      { _id: _id },
      { $set: { status: status } }
    );
    res.send({
      code: 200,
      msg: '修改成功',
      data: result
    });

  } catch (error) {
    console.error('修改失败:', error);
    res.status(500).send({
      code: 500,
      msg: '修改失败',
      error: error.message
    });
  }
});

//食品数据
router.get("/foodlist", async (req, res) => {
  const foodlist = await FoodModel.find();

  res.send({
    code: 200,
    data: foodlist,
  });
});
//食品分类
router.get("/foodCatelist", async (req, res) => {
  const foodCatelist = await FoodCateModel.find();

  res.send({
    code: 200,
    data: foodCatelist
  })
})
//vip金额
router.get('/vipPrice', async (req, res) => {
  const vipPrice = await vipPriceModel.find()
  res.send({
    code: 200,
    price: vipPrice
  })
})

//vip金额添加
router.post('/vipPriceAdd', async (req, res) => {
  await vipPriceModel.create(req.body)
})


//vip金额修改
router.post('/vipPriceEdit', async (req, res) => {
  console.log(req.body, '修改+_+_+_+_+_+_');

  // await vipPriceModel.updateOne({_id:req.body._id},{$set:{price,num:req.body.frequency }})

  // const {price,frequency}=req.body
  // const result = await vipPriceModel.updateOne(
  //   {_id:req.body._id},
  //   {$set:{price,num:frequency }}
  // );

  try {
    // 1. 检查 `_id` 是否存在
    if (!req.body._id) {
      return res.status(400).json({ error: "缺少参数 _id" });
    }

    // 2. 提取可更新的字段（防止恶意修改）
    const { price, num } = req.body;

    // 3. 使用正确的 updateOne 语法
    const result = await vipPriceModel.updateOne(
      { _id: req.body._id }, // ⚠️ 注意：条件必须是对象形式
      { $set: { price, num } } // 只更新允许的字段
    );

    // 4. 检查是否匹配到文档
    if (result.matchedCount === 0) {
      return res.status(404).json({ error: "未找到匹配的 VIP 记录" });
    }

    res.status(200).json({ success: true, updated: result });
  } catch (err) {
    console.error("更新 VIP 出错:", err);
    res.status(500).json({ error: "服务器错误" });
  }
})

//登录
router.post("/login", async function (req, res) {
  try {
    const { username } = req.body;
    // 这里应该添加用户验证逻辑，这里简单示例
    const user = await registerModel.findOne({ username });

    if (!user) {
      return res.send({
        code: 401,
        msg: "用户名或密码错误"
      });
    }

    // 生成访问token (15分钟过期)
    const accessToken = jwt.sign(
      { userId: user._id },
      'your-secret-key', // 应该使用环境变量存储密钥
      { expiresIn: '5s' }
    );

    // 生成刷新token (7天过期)
    const refreshToken = jwt.sign(
      { userId: user._id },
      'your-refresh-secret-key', // 应该使用环境变量存储密钥
      { expiresIn: '7d' }
    );

    // 将refreshToken存储到数据库
    await registerModel.updateOne(
      { _id: user._id },
      { refreshToken }
    );

    res.send({
      code: 200,
      msg: "登录成功",
      user,
      data: {
        accessToken,
        refreshToken,
        userInfo: {
          username: user.username,
          // 其他用户信息...
        }
      }
    });
  } catch (error) {
    console.error('登录错误:', error);
    res.status(500).send({
      code: 500,
      msg: "服务器错误"
    });
  }
});

// 刷新token接口
router.post("/refreshToken", async function (req, res) {
  try {
    const { refreshToken } = req.body;

    if (!refreshToken) {
      return res.status(401).send({
        code: 401,
        msg: "缺少刷新token"
      });
    }

    // 验证refreshToken
    const decoded = jwt.verify(refreshToken, 'your-refresh-secret-key');
    const user = await registerModel.findOne({
      _id: decoded.userId,
      refreshToken
    });

    if (!user) {
      return res.status(401).send({
        code: 401,
        msg: "无效的刷新token"
      });
    }

    // 生成新的accessToken
    const newAccessToken = jwt.sign(
      { userId: user._id },
      'your-secret-key',
      { expiresIn: '15m' }
    );

    res.send({
      code: 200,
      msg: "刷新成功",
      data: {
        accessToken: newAccessToken
      }
    });
  } catch (error) {
    console.error('刷新token错误:', error);
    res.status(401).send({
      code: 401,
      msg: "刷新token已过期或无效",
      data: foodCatelist,
    });
  }
});

//登录
// router.post("/login", async function (req, res) {
//   let { username, password } = req.body;
//   let result = await registerModel.find({ username, password });
//   if (result.length > 0) {
//     res.send({
//       code: 200,
//       msg: "登录成功",

//     });
//   } else {
//     res.send({
//       code: 500,
//       msg: "登录失败",
//     });
//   }
// });

// 引入腾讯云人脸识别包
let tencentcloud = require("tencentcloud-sdk-nodejs-iai");
// 人脸识别后端
router.post("/faceLogin", async function (req, res) {
  const base64 = req.body.base64;
  if (!base64) {
    return res.json({
      code: -2,
      msg: "前端未传递图片，请检查请求数据",
    });
  }
  const IaiClient = tencentcloud.iai.v20200303.Client;
  const clientConfig = {
    credential: {
      secretId: "AKIDCF5jFahdO0UlurcBZkjV3VnroX4NTM4Z",
      secretKey: "KWUEl370gAQSGrGUWMzOaaNwKUVINHQO",
    },
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };
  const client = new IaiClient(clientConfig);
  const params = {
    GroupIds: ["10001"],
    Image: base64,
    NeedPersonInfo: 1,
    QualityControl: 0,
    FaceMatchThreshold: 85,
  };
  try {
    const { Results } = await client.SearchFaces(params);
    if (Results[0].Candidates.length === 0) {
      res.json({
        code: -1,
        msg: "该人员没有注册",
      });
      return;
    }
    const { FaceId, Gender, PersonId, PersonName } = Results[0].Candidates[0];
    res.json({
      code: 0,
      data: {
        FaceId,
        Gender,
        PersonId,
        PersonName,
      },
      msg: "识别成功",
    });
  } catch (error) {
    console.error("人脸识别请求出错:", error);
    res.json({
      code: -1,
      msg: "人脸识别请求出错，请稍后重试",
    });
  }
});

// 处理添加人脸识别人员的请求
app.post("/add-person", async (req, res) => {
  const { personId, personName, imageBase64 } = req.body;
  const tencentcloud = require("tencentcloud-sdk-nodejs-iai");
  const IaiClient = tencentcloud.iai.v20200303.Client;
  // 实例化一个认证对象，入参需要传入腾讯云账户 SecretId 和 SecretKey，此处还需注意密钥对的保密
  // 代码泄露可能会导致 SecretId 和 SecretKey 泄露，并威胁账号下所有资源的安全性
  // 以下代码示例仅供参考，建议采用更安全的方式来使用密钥
  // 请参见：https://cloud.tencent.com/document/product/1278/85305
  // 密钥可前往官网控制台 https://console.cloud.tencent.com/cam/capi 进行获取
  const clientConfig = {
    credential: {
      secretId: "AKIDCF5jFahdO0UlurcBZkjV3VnroX4NTM4Z",
      secretKey: "KWUEl370gAQSGrGUWMzOaaNwKUVINHQO",
    },
    // 使用临时密钥示例
    /*
  credential: {
    secretId: "SecretId",
    secretKey: "SecretKey",
    token: "Token",
  }
*/
    region: "ap-beijing",
    profile: {
      httpProfile: {
        endpoint: "iai.tencentcloudapi.com",
      },
    },
  };

  //支付宝支付
  router.get('/', function (req, res, next) {
    res.render('index', {
      title: 'Express'
    });
  });

  // 图像验证码



  // 房间查询
  // router.post('/roomlist', async (req, res) => {
  //   const list = await roomModel.find()
  //   res.send({
  //     code: 200,
  //     list
  //   })
  // })




  // 手机短信验证
  // 实例化要请求产品的client对象,clientProfile是可选的
  const client = new IaiClient(clientConfig);
  const params = {
    GroupId: "10001",
    PersonName: String(Date.now()),
    PersonId: String(Date.now()),
    Gender: 1,
    PersonExDescriptionInfos: [
      {
        PersonExDescriptionIndex: 1,
        PersonExDescription: "1",
      },
    ],
    Image: imageBase64,
    QualityControl: 1,
  };
  client.CreatePerson(params).then(
    (data) => {
      console.log(data);
    },
    (err) => {
      console.error("error", err);
    }
  );
  res.send({
    code: 0
  })
});



//获取订单的数据
router.get('/listhjc', async (req, res) => {
  let list = await orderModel.find()
  res.send({
    code: 200,
    list
  })
})


// 添加酒店订单
router.post('/addorder', async (req, res) => {
  await orderModel.create(req.body)
  res.send({
    code: 200,

  })
})


//下载alipay-sdk@3  
//引入
let AlipaySdk = require("alipay-sdk").default
let AlipaySdkForm = require("alipay-sdk/lib/form").default
router.post("/alipay", async (req, res) => {
  console.log(req.body, 'req');

  // 1-配置信息
  // 实例化客户端  商家信息
  const alipaySdk = new AlipaySdk({
    // 设置应用 ID
    appId: '2021000147672708',
    // 设置应用私钥
    // privateKey: "MIIEowIBAAKCAQEAy4z4UKAKZaCe+NtCaHYrq+rvrM73hZlo9uVytf90R/XlBFOlIYpMHBrEwgvZwJIcbqMJnAbqbVQt8Do6UzK1Az/HdM93qpegLOF9WtValdmLhqPVo3nL0ZmO3xDoGgEsrm/5FF77jpuNz9X6mM27fafR8KgpJz3lFT13ORNynZeL94RdUvKyVGrTaTIqYpvMDnLR3w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B92uXDd+AnBn0fh5l7VrRlpTZio1UEZiE3gkwTTqYcf5atL8cdR1Un8Zn8sh/RMWKOAd7nHSDmlP4IxW6cvrxcDXb4KKxgmcgAlAyq27Egk+wwT5QS+v/s+esXm4GwBFs6dWczrSxFUp+PVKXMkhF4N/PHO8X8u/GbRjRdEJC7S0SpLVEYhIo//9/sI50bOrlmxSdKPXMbDN7EQT6fcEIrJgjxNyEsoamS4IHKcRWtPbRsXuM+btnpnjmkyMXeztg/NuBn4Bl46gpHuvtFWlNbZlKabyFCEnrIbMlI7RfcM1nOGUDPTgOulgESlkn7Z8cK0xFO7FvJQIDAQAB",
    // 密钥类型，请与生成的密钥格式保持一致，参考平台配置一节
    // keyType: 'PKCS1',
    // 设置网关地址，默认是 https://openapi.alipay.com
    // endpoint: 'https://openapi.alipay.com',
    gateway: "https://openapi-sandbox.dl.alipaydev.com/gateway.do", //支付宝网关
  });
  const formData = new AlipaySdkForm();
  // 同步通知  支付成功之后打开前端的某一个路由

    formData.addField("returnUrl", `http://localhost:5173/${req.body.name=='Vip充值'?'vip':req.body.name=='李家饭馆'?"food":'tabber/first'}`)


  //支付参数
  formData.addField("bizContent", {
    out_trade_no: Date.now(), //订单编号 一个订单号只能支付一次 不能重复支付
    product_code: "FAST_INSTANT_TRADE_PAY",
    subject: req.body.name,
    body: "详情 数据",
    total_amount: req.body.price

  })
  //请求支付宝的第三方接口
  // pc端支付 alipay.trade.page.pay
  // H5端支付 alipay.trade.wap.pay
  let result = await alipaySdk.exec("alipay.trade.wap.pay", {}, {
    formData: formData
  })
  // 修改数据库的信息  将你们的订单信息存储起来
  res.send(result)


})

//获取订单的数据
router.get('/searcid', async (req, res) => {
  try {
    const { _id } = req.query // 从 URL 参数获取 _id
    if (!_id) {
      return res.status(400).send({ code: 400, message: '缺少 _id 参数' })
    }
    const order = await orderModel.findById(_id) // 使用 Mongoose 查询
    if (!order) {
      return res.status(404).send({ code: 404, message: '订单不存在' })
    }
    res.send({ code: 200, list: order })
  } catch (error) {
    console.error('查询订单失败:', error)
    res.status(500).send({ code: 500, message: '服务器错误' })
  }
})


router.post('/roomlist', async (req, res) => {
  const list = await roomModel.find()
  res.send({
    code: 200,
    list
  })
})

// 更新订单离店时间
router.post('/update', async (req, res) => {
  const list = req.body
  console.log(list);

  // 如果有nights参数，计算并设置end日期
  if (list.nights) {
    try {
      // 获取原始订单数据
      const order = await orderModel.findById(list._id)
      if (order) {
        let baseDate

        // 如果订单已经有end日期且是在更新nights，则从end日期开始计算
        if (order.end && !list.start) {
          baseDate = new Date(order.end)
        }
        // 否则从start日期开始计算（新订单或明确更改了start日期）
        else if (order.start) {
          baseDate = new Date(order.start)
        }

        if (baseDate) {
          // 计算新的end日期
          const endDate = new Date(baseDate)
          endDate.setDate(baseDate.getDate() + parseInt(list.nights))

          // 将计算出的end日期添加到更新数据中
          list.end = endDate
        }
      }
    } catch (err) {
      console.error('计算end日期时出错:', err)
    }
  }

  await orderModel.updateOne({ _id: list._id }, list)
  res.send({
    code: 200
  })
})

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

module.exports = router;

